<template>
  <a-input-group compact>
    <a-input 
      :value="value" 
      @blur="handleInputBlur"
      @change="(e) => changePath(e.target.value)"
      style="width: calc(100% - 33px)" 
    />
    <a-button type="primary" @click="selectFile">
      <template #icon>
        <FolderOpenOutlined />
      </template>
    </a-button>
  </a-input-group>
</template>

<script setup>
import { Form } from 'ant-design-vue'
import { FolderOpenOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  value: String,
  'type': {
    type: String,
    default: 'directory'
  },
  extensions: Array
})

const emit = defineEmits(['update:value'])

const formItemContext = Form.useInjectFormItemContext()

const changePath = path => {
  emit('update:value', path)
  formItemContext.onFieldChange();
}

function handleInputBlur(){
  formItemContext.onFieldBlur()
}

async function selectFile() {
  let result = null;
  if(props.type === 'directory'){
    result = await window.electronAPI.openDir()
  }
  if(props.type === 'file'){
    result = await window.electronAPI.openFile(props.extensions)
  }
  if(result){
    emit('update:value', result)
    formItemContext.onFieldBlur()
  }
}
</script>
